package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;

import com.itheima.dao.MenuDao;

import com.itheima.pojo.Menu;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;



    @Autowired
    private MenuDao menuDao;

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
             LinkedHashSet<Menu> menus = menuDao.findById(roleId);
            role.setPermissions(permissions);//让角色关联权限
            role.setMenus(menus);
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    @Override

    public PageResult QueryPage(Integer currentPage, Integer pageSize, String queryString) throws Exception {
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.queryPage(queryString);


        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user,Integer[]roleIds) {
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        password = bCryptPasswordEncoder.encode(password);
        user.setPassword(password);
        userDao.add(user);
        Integer id = user.getId();
        this.setUserAndRole(id,roleIds);
    }
    //建立用户与角色多多的关系表
    public void setUserAndRole(Integer usrId,Integer[] roleIds){
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("usrId",usrId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }




    public List<Object> getMenu(String username) {
        List<Object> menuList = new ArrayList<>();
        User findUser = findByUsername(username);
        Set<Role> roles = findUser.getRoles();
        HashSet<Menu> menus = new HashSet<>();
        if (roles!=null&&roles.size()>0){
            for (Role role : roles) {
                LinkedHashSet<Menu> set = role.getMenus();
                for (Menu menu : set) {
                    if (menu.getParentMenuId()==null){
                        Map map = menu2Map(menu);
                        Integer menuId = menu.getId();
                        List<Map> list=new ArrayList<>();
                        List<Menu> byMenuId = menuDao.findByMenuId(menuId);
                        for (Menu menu1 : byMenuId) {
                            list.add(menu2Map(menu1));
                        }
                        map.put("icon",menu.getIcon());
                        map.put("children",list);
                        menuList.add(map);
                    }
                }
            }
        }
        return menuList;
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    //删除用户时，需要先删除中间关系表，再删除
    public void delete(Integer id) {
     User user= userDao.findUserAndRoleById(id);
      if(user!=null){
          userDao.deleteUserAndRole(id);//删除中间表
      }
      userDao.deleteUserById(id);//删除用户表的用户

    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.edit(user);
        //清理当前中间表的关系
        userDao.deleteUserAndRole(user.getId());
        //重新建立当前检查组和检查项的关联关系
        Integer checkGroupId = user.getId();
        this.setUserAndRole(checkGroupId,roleIds);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    private Map menu2Map(Menu menu){
        HashMap<String, Object> map = new HashMap<>();
        map.put("path",menu.getPath());
        map.put("title",menu.getName());
        map.put("linkUrl",menu.getLinkUrl());
        return map;
    }

}
